import { ILine, IVec } from "@/models/geometry";
import { IPoint } from "@/models/gui";

function segmentCompare (a: ILine, b: ILine): number {
  const ax = Math.min(a.p1.x, a.p2.x);
  const ay = Math.min(a.p1.y, a.p2.y);
  const bx = Math.min(b.p1.x, b.p2.x);
  const by = Math.min(b.p1.y, b.p2.y);
  if (ax != bx) {
    return ax > bx ? 1 : -1;
  } else {
    return ay > by ? 1 : -1;
  }
}

export function sortSegments (segments: ILine[]): ILine[] {
  return segments.concat().sort(segmentCompare);
}

interface ISquare {
  left: number;
  right: number;
  top: number;
  bottom: number;
}

// current + t * dir = (x, y)

function normalVec (vec: IVec): IVec {
  const l = (vec.x ** 2 + vec.y ** 2) ** .5;
  return {
    x: vec.x / l,
    y: vec.y / l
  };
}

export class Chessboard {
  private squares: ISquare[] = [];  

  addSegment (segment: ILine) {
    let current = segment.p1;
    const end = segment.p2;
    const dir = normalVec({
      x: segment.p2.x - segment.p1.x,
      y: segment.p2.y - segment.p1.y,
    });
    let square = this.findSquare(current);
    while (true) {
      if (!square) {
        break;
      }
      if (end.y > square.top) {
        const t = (square.top - current.y) / dir.y;
        const x = current.x + t * dir.x;
        if (x < square.left) {
          square = this.getLeftSquare(square);
        } else if (x <= square.right) {
          square = this.getUpSquare(square);
        } else {
          square = this.getRightSquare(square);
        }
        current = { x: current.x + t * dir.x, y: current.y + t * dir.y };
      } else if (end.y >= square.bottom) {
        if (end.x < square.left) {
          square = this.getLeftSquare(square);
          
        } else if (end.x <= square.right) {
          square = null;
        } else {
          square = this.getRightSquare(square);
        }
      } else {
        
      }
    }
  }

  findSquare (point: IPoint): ISquare {
    return null;
  }

  getLeftSquare (square: ISquare): ISquare {
    return null;
  }

  getUpSquare (square: ISquare): ISquare {
    return null;
  }

  getRightSquare (square: ISquare): ISquare {
    return null;
  }

  getDownSquare (square: ISquare): ISquare {
    return null;
  }



}


/*
  平面切割成n个盒子
  和每个盒子有交集的在盒子上加个索引
  每个点计算从盒子取数据
*/